#!/bin/bash

# input
read -p "Please enter Go version (default: 1.20.7):" GO_VERSION

read -p "Please enter the user name to config Go env (default: root):" USERNAME

if [ -z "$GO_VERSION" ]; then
    GO_VERSION="1.20.7"
fi

if [ -z "$USERNAME" ]; then
    USERNAME_DIR=$HOME
else
    USERNAME_DIR=/home/$USERNAME
fi

check_command() {
    command -v "$1" >/dev/null
    if [ $? -ne 0 ]; then
        echo "Command not found, please install $1 command and try again."
        exit 1
    fi
}

get_os_type() {
    if [ "$(uname)" == "Darwin" ]; then
        os="darwin"
    elif [ "$(uname)" == "Linux" ]; then
        os="linux"
    else
        echo "Failed to get system type."
        exit 1
    fi
}

get_arch() {
    if [ $(arch) == "x86_64" ]; then
        arch="amd64"
    elif [ $(arch) =~ "aarch64" ]; then
        arch="arm64"
    else
        echo "Failed to get system arch."
        exit 1
    fi
}

install_go() {
    wget https://golang.google.cn/dl/go"$GO_VERSION"."$os"-"$arch".tar.gz

    rm -rf /usr/local/go

    tar -xzf go"$GO_VERSION"."$os"-"$arch".tar.gz -C /usr/local
    ln -s /usr/local/go/bin/* /usr/bin/

    rm -rf go"$GO_VERSION"."$os"-"$arch".tar.gz

    go version

    mkdir -p $USERNAME_DIR/.gopath/src
    mkdir -p $USERNAME_DIR/.gopath/pkg
    mkdir -p $USERNAME_DIR/.gopath/bin

    chown -R $USERNAME $USERNAME_DIR/.gopath/
    chown -R $USERNAME $USERNAME_DIR/.gopath/

    echo "export GOROOT=/usr/local/go" >>$USERNAME_DIR/.bashrc
    echo -e "export GOPATH=\$HOME/.gopath" >>$USERNAME_DIR/.bashrc
    echo -e "export PATH=\$PATH:\$GOROOT/bin:\$GOPATH/bin" >>$USERNAME_DIR/.bashrc
    source $USERNAME_DIR/.bashrc

    go env -w GOPROXY=https://goproxy.cn,direct
    
    go env
}

main() {
    check_command "wget"
    get_os_type
    get_arch
    install_go
}

main
